<template>
	<div>
		<van-form @submit="onSubmit">
			<van-cell-group inset>
				<van-field v-model="formData.name" name="缘主姓名" label="缘主姓名" placeholder="需要保存时,请输入姓名"
					:rules="[{ required: true, message: '请填写用户名' }]" />
				<van-field name="sex" label="性别">
					<template #input>
						<van-radio-group v-model="formData.sex" direction="horizontal">
							<van-radio :name="1">男</van-radio>
							<van-radio :name="0">女</van-radio>
						</van-radio-group>
					</template>
				</van-field>

				<van-field v-model="formData.date" readonly is-link clickable name="date" label="出生日期"
					@click="showPicker=true">
				</van-field>

			</van-cell-group>
			<div style="margin: 16px;">

				<van-button v-if="paipan==false" round block type="primary" @click="startPaipan">
					<van-badge content="免费">
						八字排盘&nbsp;&nbsp;&nbsp;
					</van-badge>
				</van-button>
				<van-button v-else round block @click="clearPaipan">
					重新排盘
				</van-button>
			</div>
		</van-form>

		<div v-if="paipan==true">
			<van-divider content-position="center">八字排盘信息</van-divider>
			<van-space direction="vertical" fill :size="1" class="result">

				<span>八字: {{paipanInfo.bazi}}</span>
				<span>{{paipanInfo.yun[0]}}</span>
				<span>{{paipanInfo.yun[1]}}</span>
				<span>{{paipanInfo.yun[2]}}</span>
				<span>{{paipanInfo.fullString}}</span>
				<div style="margin-top:15px" class="fixed-bottom">
					<div style="width:90%;margin:0 auto;">
						<van-button round type="success" block @click="createOrder">八字分析（限时：6元/次，<span
								style="text-decoration: line-through;">原价：50元/次</span>）</van-button>
					</div>

					<van-divider>法不轻传，道不贱卖，师不顺路，医不叩门</van-divider>
				</div>
			</van-space>
		</div>

		<van-popup v-model:show="showPicker" destroy-on-close position="bottom">
			<van-date-picker :model-value="pickerValue" title="选择出生日期" :min-date="minDate" :max-date="maxDate"
				confirm-button-text="选择时间" @confirm="onConfirmDate" @cancel="showPicker = false">
				<template #title>
					<van-tabs v-model:active="formData.dateType" type="card" style="width:50%">
						<van-tab title="农历"></van-tab>
						<van-tab title="公历"></van-tab>
					</van-tabs>
				</template>
			</van-date-picker>
		</van-popup>
		<van-popup v-model:show="showTimePicker" destroy-on-close position="bottom">
			<van-time-picker :model-value="pickerTimeValue" title="选择出生时间" @confirm="onConfirmTime"
				@cancel="showTimePicker = false">
			</van-time-picker>
		</van-popup>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		fetchBazi,
		testBazi,
		getBaziOrder
	} from '@/api/bazi'
	import {
		showDialog
	} from 'vant';
import { Form } from 'tdesign-vue-next';
import {tenpayPrepayInfo} from '@/api/pay'
import $eventBus from '@/utils/eventBus'
import {useWebsocketStore} from '@/store'
import { tenpay} from '../payment'

const websocketStore=useWebsocketStore()
	const paipan = ref(false)
	const username = ref('');
	const formData = ref({
		name: '',
		sex: 1,
		date: '',
		dateType: 0
	})
	const paipanInfo = ref({
		fullString: '',
		bazi: '',
		yun: []
	})
	const startPaipan = () => {
		if (formData.value.date == '') {
			showNotify({
				type: 'warning',
				message: '请选择出生时间'
			})
		} else {
			fetchData()
		}

	}
	const initData = () => {
		let pp = localStorage.getItem('paipan')
		if (pp) {
			paipanInfo.value = JSON.parse(pp)
			paipan.value = true;
			let user = JSON.parse(localStorage.getItem('paipanUser'))
			if (user)
				formData.value = user
		}
	}
	const fetchData = () => {
		fetchBazi(formData.value)
			.then(res => {
				var ret = res.result
				paipanInfo.value = ret
				paipan.value = true
				localStorage.setItem('paipan', JSON.stringify(paipanInfo.value))
				localStorage.setItem('paipanUser', JSON.stringify(formData.value))
			})
	}
	const createOrder = () => {
		//创建订单
		formData.value.connId=websocketStore.wsId
		getBaziOrder(formData.value)
		.then(res0=>{
			if(res0.code==401)
			{
				$eventBus.emit('OpenLoginEvent')
				return;
			}
			if(res0.success)
			{
				let order=res0.result
				if(order.order_status==1)
				{
					//调用支付 
					let s=localStorage.getItem('userInfo')
					let user=JSON.parse(s)
					tenpayPrepayInfo({
						scene:1,
						appId:'wx7c829604a62b02e8',
						openId:user.openId,
						orderNo:order.orderno,
						orderName:order.order_name,
						payAmount:order.pay_amount,
						attach:''
					})
					.then(res=>{
						let payParams=res.data
						if(res.result)
						{
							payParams=res.result.data
						}
						tenpay(payParams)
					})
				}else
				{
					test(order.orderno)
				}
			}else
			{
				showNotify({
					type: 'warning',
					message: res0.msg
				})
			}
		})
		.catch(e=>{
			console.log('createOrder',JSON.stringify(e))
			if(e.code==401)
			{
				$eventBus.emit('OpenLoginEvent')
				return;
			}
		})
		
	}
	const test=(orderNo)=>{
		testBazi({orderNo:orderNo})
		.then(res=>{
			if(res.success)
			{
				showNotify({
					type: 'primary',
					message: '点击测算记录，查看结果'
				})
			}else
			{
				showNotify({
									type: 'warning',
									message: res.msg
								})
			}
		})
	}
	const minDate = new Date(1960, 1, 1)
	const maxDate = new Date();

	const onSubmit = (values) => {
		console.log('submit', values);
	};

	const showPicker = ref(false);
	const showTimePicker = ref(false)
	const pickerValue = ref([]);
	const pickerTimeValue = ref([])
	const onConfirmDate = ({
		selectedValues
	}) => {
		formData.value.date = selectedValues.join('-');
		pickerValue.value = selectedValues;
		showPicker.value = false;
		showTimePicker.value = true;
		clearPaipan()
	}
	const onConfirmTime = ({
		selectedValues
	}) => {
		formData.value.date += ' ' + selectedValues.join(':');
		pickerTimeValue.value = selectedValues;
		showTimePicker.value = false;
		clearPaipan()
	}
	const clearPaipan = () => {
		localStorage.removeItem('paipan')
		localStorage.removeItem('paipanUser')
		paipan.value = false
	}
	onMounted(() => {
		initData()
	})
</script>

<style scoped>
	.result {
		margin-top: 10px;
		margin-left: 10px;
		margin-right: 10px;
	}

	.fixed-bottom1 {
		position: fixed;
		bottom: 50px;
		/* 根据 Tabbar 的高度调整 */
		left: 0;
		right: 0;
		background-color: white;
		text-align: center;
		padding: 10px 0;

	}
</style>